/*************************************************************************
    > File Name: php_libc.c
    > Author: colinqin
    > Mail: colinqin@fenqile.com 
    > Created Time: Mon 31 Jul 2017 08:01:44 PM CST
 ************************************************************************/

#include <stdio.h>
#include <sapi/embed/php_embed.h>
#include <string>
#include <iostream>
#include "php_libc.h"

using namespace std;

#ifdef ZTS
    void ***tsrm_ls;
#endif
/* Extension bits */
zend_module_entry php_mymod_module_entry = {
    STANDARD_MODULE_HEADER,
    "mymod", /* extension name */
    NULL, /* function entries */
    NULL, /* MINIT */
    NULL, /* MSHUTDOWN */
    NULL, /* RINIT */
    NULL, /* RSHUTDOWN */
    NULL, /* MINFO */
    "1.0", /* version */
    STANDARD_MODULE_PROPERTIES
};
/* Embedded bits */
void startup_php(void)
{
    int argc = 1;
    char *argv[2] = { "embed5", NULL };
    php_embed_init(argc, argv PTSRMLS_CC);
    zend_startup_module(&php_mymod_module_entry);
}

void execute_php(char *filename, string str)
{
	startup_php();
    zend_first_try {
        char *include_script;
        spprintf(&include_script, 0, "include '%s';", filename);
        zend_eval_string(include_script, NULL, filename TSRMLS_CC);
		script_handler(str);
        efree(include_script);
    } zend_end_try();

    php_embed_shutdown(TSRMLS_CC);
}


/*
* key 10.1.48.58:10654->10.1.48.58:22456
* value json_string
*
*/
 void script_handler(string &str){
	zval z_funcname;  
	ZVAL_STRING(&z_funcname, "handler", 1);  
	  
	zval *zp_value;  
	MAKE_STD_ZVAL(zp_value);  
	ZVAL_STRING(zp_value, str.c_str(), 1);  
	  
	zval z_retval;  
	zval *z_params[] = {zp_value};  
	int call_ret = call_user_function(EG(function_table), NULL, &z_funcname, &z_retval,
		sizeof(z_params) / sizeof(z_params[0]), z_params TSRMLS_CC);  
	
	int func_ret = Z_LVAL_P(&z_retval);  
	  
	zval_ptr_dtor(&zp_value);  
	zval_dtor(&z_funcname);  
	zval_dtor(&z_retval);  
	  
	if (call_ret < 0 || func_ret < 0) {  
	//    base->log_.LOG_P_PID(LOG_FATAL, "call_user_function fail. call_ret=%d func_ret=%d\n", call_ret, func_ret);  
		printf("call_user_function fail. call_ret=%d func_ret=%d\n", call_ret, func_ret);
	}  
}
